<?php
namespace app\member\controller;
class Task extends Common{
    function __construct(){
        parent::__construct();
        $this->assign('_nav',json_encode(config("navs.2.children"),JSON_UNESCAPED_UNICODE));
    }
    /**
     * #创建任务#
     * 任务参数请参照 member/controller/msg.php
     * @return [type] [description]
     */
    function newTask(){
        $user=$this->user;
        
        if(request()->isPost()){
            $post=input('post.');
            $validate=$this->validate($post,[
                'event|任务指令Event'=>'require',
                'action|任务指令Action'=>'require',
                'title|任务标题'=>'require',
            ]);
            if(true!==$validate){
                $this->error($validate);
            }
            $remark=model('Taskoptions')->getTaskEvent($post['event'],$post['action']);
            if(empty($remark)){
                $this->error(lang('Instruction event does not exist'));
            }
            $post['type']=$remark['type'];
            $post['remark']=$remark['remark'];
            // 组装任务数据
            $data=$this->getTaskData($post,$user['id']);
            $rs=success();
            if(empty($data['dev'])){
                $this->error('请先选择设备');
            }
            // 发朋友圈
            if($data['event']==='friends'&&$data['action']==1){ 
                if(empty($data['msg'])){
                    $this->error('内容不能为空');
                }
            }
            // 查询手机号是否微信号
            if($data['event']==='extraTask'&&$data['action']==1){ 
                if(empty($data['dev'])||empty($data['software'])){
                    $this->error('请至少选择一个微信执行任务');
                }
                $rs=model('mobile')->createQueryWx($data,$user['id']);
            }else{
                //多媒体文件ID组
                $files=input('files/a',[]);
                // 创建任务 
                $rs=$this->createTask($data,$user['id'],$files);
            }
            //dump($data);
            
            if($rs['success']){
                $this->success(lang('Create success'));
                die;
            }
            $this->error($rs['msg']);
        }
        

        $taskgroup=model('taskgroup')->readAll(['status'=>1,'pc'=>1],0,['with'=>'taskoptionspc']);
        $this->assign('taskgroup',$taskgroup);
        //p($taskgroup->toArray());
        $options=[
            'field'=>'id,name',
            'withCount'=>'device',
        ];
        $dev_group=model('group')->readAll(['member_id'=>$user['id'],'type'=>0],0,$options);
        $this->assign('dev_group',$dev_group);
        $this->assign('tasknav',config('task.'));
        // 素材分组
        $cate=controller('category')->getCates();
        $this->assign('cate',json_encode($cate));
        // 默认素材组ID
        $cate_id=isset($cate[0])?$cate[0]['id']:0;
        $this->assign('cate_id',$cate_id);
        // 默认显示素材组
        $source=controller('source')->getSources($cate_id,'',['uid'=>$user['id']]);
        $this->assign('source',$source);

        //p($source);
        return view();
    }
    /**
     * #新任务列表#
     * @return [type] [description]
     */
    function task(){
        $list=model($this->tasking)->getTask(['status'=>0,'member_id'=>$this->user['id']],true);
        $this->assign('list',$list);
        return view();
    }
    /**
     * #待执行任务(候选任务)#
     * @return [type] [description]
     */
    function afterTasking(){
        $list=model($this->tasking)->getTask(['status'=>1,'member_id'=>$this->user['id']],true);
        $this->assign('list',$list);
        return view();
    }
    /**
     * #进行中任务#
     * @return [type] [description]
     */
    function tasking(){
        $list=model($this->tasking)->getTask(['status'=>2,'member_id'=>$this->user['id']],true);
        $this->assign('list',$list);
        return view();
    }
    /**
     * #已完成任务#
     * @return [type] [description]
     */
    function tasked(){
        $list=model($this->tasked)->getTask(['member_id'=>$this->user['id']],true);
        $this->assign('list',$list);
        return view();
    }

    function taskHtml(){
        $user=$this->user;
        $device=model('device')->readAll(['member_id'=>$user['id']],0,[
            'field'=>'id,name'
        ]);
        $this->assign('device',$device);

        return view();
    }
    // 将新任务直接加入候选区（将新任务的执行时间更改为立即执行）
    function startTask($id=0){
        if(request()->isPost()){
            if($id<=0){
                return json(lang('Data does not exist'),1);
            }
            $member_id=$this->user['id'];
            $has=model($this->tasking)->read(['id'=>$id,'member_id'=>$member_id]);
            if(empty($has)){
                return json(lang('Data does not exist'),1);
            }
            $edit=model($this->tasking)->edit(['id'=>$id,'status'=>1,'start_time'=>time()]);
            $msg=null;
            if($edit){
                $rs=$this->runTask($member_id);
                if(!empty($rs)&&$rs['status']){
                    return json(lang('Successful operation'));
                }
                $msg=isset($rs['msg'])?$rs['msg']:lang('Failed operation');

                // 此处直接返回成功 $rs为空实际已执行成功  （待完善）
                $msg=lang('Successful operation');
                return json($msg);
            }
            if(empty($msg)){
                $msg=lang('Failed operation');
            }
            return json($msg,1);
        }
    }
    /**
     * #任务完成#
     * @param  integer $id 任务ID
     * @return json
     */
    function finish($id=0){
        if($id<=0){
            $this->error(lang('Data does not exist'));
        }
        $uid=$this->user['id'];
        $task=model('task_device')->read(['id'=>$id,'member_id'=>$uid],'device_id');
        if(empty($task)){
            return json(lang('Data does not exist'),1);
        }
        // 扩展任务的额外处理
        

        $rs=model('task_device')->nextTask($uid,$task['device_id']);
        if($rs['success']){
            $this->success(lang('Successful operation'));
            die;
        }else{
            $msg=$rs['msg'];
            if(empty($msg)){
                $msg=lang('Failed operation');
            }
            $this->error($msg);
        }
    }
    /**
     * #删除任务#{执行中的任务不可删除}
     * @param  integer $id 任务ID
     * @return json
     */
    function del($id=0){
        if(request()->isAjax()||request()->isPost()){
            $ids=input('ids/a',[]); // 多项删除
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $wxmsg_task_id=$this->user['wxmsg_task_id'];
            if($id==$wxmsg_task_id){
                $this->error('该消息采集任务不可删除，可在用户中心中设置采集间隔');
            }
            $where=['id'=>$id,'member_id'=>$member_id];
            $_map=['task_id'=>$id];
            if(!empty($ids)){
                $i=array_search($wxmsg_task_id, $ids);

                if(false!==$i){
                    unset($ids[$i]);
                }
                $where=[
                    'member_id'=>$member_id,
                    'id'=>['id','in',$ids]
                ];
                $_map=['task_id'=>['task_id','in',$ids]];
            }
            
            $tasking=$this->tasking;
            $table=input('table/s',$tasking);
            $model=$table==$tasking?model($tasking):model($this->tasked);
            $del=$model->del($where);
            if($del){
                $device=model('task_device')->readAll($_map,0,['field'=>'device_id']);
                // 执行中
                $deving=model('task_device')->readAll(array_merge($_map,['state'=>1]),0,['field'=>'device_id']);
                if(count($device)){
                    // 移除队列
                    $_del=model('task_device')->del($_map);
                    if($_del){
                        
                        foreach ($device as $k => $v) {
                            $device[$k]=$v['device_id'];
                        }
                        if(count($deving)){
                            // 移除了正在执行的任务队列应该进行 下一个任务
                            $taskDevModel=model('task_device');
                            foreach ($deving as $k => $v) {
                                $taskDevModel->nextTask($member_id,$v['device_id']);
                            }
                        }else{
                            // 通知任务队列更新
                            model('task_device')->updateDev($member_id,[],$device);
                        }
                    }
                }
                
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    /**
     * 一键清空所有任务
     * @return [type] [description]
     */
    function clearAll(){
        if(request()->isAjax()||request()->isPost()){
            $user=$this->user;
            $where=[
                'member_id'=>$user['id'],
                'id'=>['id','neq',$user['wxmsg_task_id']],
            ];
            $_map=[
                'member_id'=>$user['id'],
                'task_id'=>['task_id','neq',$user['wxmsg_task_id']]
            ];
            $tasking=$this->tasking;
            $table=input('table/s',$tasking);
            $model=$table==$tasking?model($tasking):model($this->tasked);
            //p($user,1);
            $del=$model->del($where);
            if($del){
                $device=model('task_device')->readAll($_map,0,['field'=>'device_id']);
                // 执行中
                $deving=model('task_device')->readAll(array_merge($_map,['state'=>1]),0,['field'=>'device_id']);
                if(count($device)){
                    // 移除队列
                    $_del=model('task_device')->del($_map);
                    if($_del){
                        foreach ($device as $k => $v) {
                            $device[$k]=$v['device_id'];
                        }
                        if(count($deving)){
                            // 移除了正在执行的任务队列应该进行 下一个任务
                            $taskDevModel=model('task_device');
                            foreach ($deving as $k => $v) {
                                $taskDevModel->nextTask($user['id'],$v['device_id']);
                            }
                        }else{
                            // 通知任务队列更新
                            model('task_device')->updateDev($user['id'],[],$device);
                        }
                        
                    }
                }
                
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    /**
     * 关闭执行中的任务（点击完成该任务按钮）
     * @param  integer $id 任务ID
     * @return json
     */
    function close($id=0){
        if($id<=0){
            return json(lang('Data does not exist'),1);
        }
        $uid=$this->user['id'];
        $task=model('task_device')->read(['id'=>$id,'member_id'=>$uid],'device_id');
        if(empty($task)){
            return json(lang('Data does not exist'),1);
        }
        $rs=model('task_device')->nextTask($uid,$task['device_id']);
        if($rs['success']){
            return json(lang('Successful operation'));
        }else{
            $msg=$rs['msg'];
            if(empty($msg)){
                $msg=lang('Failed operation');
            }
            return json($msg,1);
        }
    }
    
}
